/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.wx.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.config.redis.RedisHandle;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.test.entity.TestTree;
import com.jeesite.modules.wx.entity.WxActivity;
import com.jeesite.modules.wx.entity.WxBusiness;
import com.jeesite.modules.wx.entity.WxBusinessGroup;
import com.jeesite.modules.wx.service.WxActivityService;
import com.jeesite.modules.wx.service.WxBusinessGroupService;
import com.jeesite.modules.wx.service.WxBusinessService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.wx.entity.WxBusinessGroupOrgConfig;
import com.jeesite.modules.wx.service.WxBusinessGroupOrgConfigService;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 机构商家分组配置Controller
 * @author wangjianxin
 * @version 2018-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/wx/wxBusinessGroupOrgConfig")
public class WxBusinessGroupOrgConfigController extends BaseController {

	@Autowired
	private WxBusinessGroupOrgConfigService wxBusinessGroupOrgConfigService;
	@Autowired
	private WxBusinessGroupService wxBusinessGroupService;
	@Autowired
	private WxBusinessService wxBusinessService;
	@Autowired
	private WxActivityService wxActivityService;
	@Autowired
	private RedisHandle redisHandle;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public WxBusinessGroupOrgConfig get(String id, boolean isNewRecord) {
		WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig = wxBusinessGroupOrgConfigService.get(id, isNewRecord);
		return wxBusinessGroupOrgConfig;
	}
	
	/**
	 * 查询列表，需要按照登录账号的机构查询
	 */
	@RequiresPermissions("wx:wxBusinessGroupOrgConfig:view")
	@RequestMapping(value = {"list", ""})
	public String list(WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig, Model model) {
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		wxBusinessGroupOrgConfig.setOfficeCode(employee.getOffice().getOfficeCode());
		model.addAttribute("wxBusinessGroupOrgConfig", wxBusinessGroupOrgConfig);
		return "modules/wx/wxBusinessGroupOrgConfigList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("wx:wxBusinessGroupOrgConfig:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<WxBusinessGroupOrgConfig> listData(WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig, HttpServletRequest request, HttpServletResponse response) {
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		wxBusinessGroupOrgConfig.setOfficeCode(employee.getOffice().getOfficeCode());
		Page<WxBusinessGroupOrgConfig> page = wxBusinessGroupOrgConfigService.findPage(new Page<WxBusinessGroupOrgConfig>(request, response), wxBusinessGroupOrgConfig);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("wx:wxBusinessGroupOrgConfig:view")
	@RequestMapping(value = "form")
	public String form(WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig, Model model) {
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		wxBusinessGroupOrgConfig.setOfficeCode(employee.getOffice().getOfficeCode());
		List<WxBusiness> wxBusinessList = new LinkedList<>();

		if(StringUtil.isNotEmpty(wxBusinessGroupOrgConfig.getId())){
			//需要查询出机构配置分组的商家
			WxBusinessGroup wxBusinessGroup = new WxBusinessGroup();
			//机构
			wxBusinessGroup.setOfficeCode(employee.getOffice().getOfficeCode());
			//分组id
			wxBusinessGroup.setConfigGroupId(Long.valueOf(wxBusinessGroupOrgConfig.getId()));
			List<WxBusinessGroup> wxBusinessGroupList = wxBusinessGroupService.findList(wxBusinessGroup);
			if(CollectionUtil.isNotEmpty(wxBusinessGroupList)){
				wxBusinessGroupOrgConfig.setWxBusinessGroup(wxBusinessGroupList.get(0));

				//查询该分组绑定的商家
				WxBusinessGroup tBusinessGroup = wxBusinessGroupOrgConfig.getWxBusinessGroup();
				String businessIds = tBusinessGroup.getBusinessIds();
				if(StringUtil.isNotEmpty(businessIds)){
					String[] arrayIds = businessIds.split(",");
					int len = arrayIds.length;
					for(int i = 0; i < len; i++){
						String businessId = arrayIds[i];
						WxBusiness wxBusiness = wxBusinessService.get(businessId);
						wxBusinessList.add(wxBusiness);
					}

				}
				//分组的商家排序
				String sortBusinessIds = tBusinessGroup.getSortBusinessIds();
				if(StringUtil.isNotEmpty(sortBusinessIds)){
					String[] sortBusinessArray = sortBusinessIds.split(",");
					int len = sortBusinessArray.length;
					for(int i = 0; i <len;i++){
						String sortBusinessId = sortBusinessArray[i];
						wxBusinessGroupOrgConfigService.setSort(i,sortBusinessId,wxBusinessGroupOrgConfig);
					}
				}
			}
		}

		//查询商家
		model.addAttribute("wxBusinessGroupOrgConfig", wxBusinessGroupOrgConfig);
		//获取分组下的所有商家
		WxBusiness wxBusiness = new WxBusiness();
		model.addAttribute("businessList", wxBusinessList);

		return "modules/wx/wxBusinessGroupOrgConfigForm";
	}

	/**
	 * 保存机构商家分组配置
	 */
	@RequiresPermissions("wx:wxBusinessGroupOrgConfig:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig) {
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		String officeCode = employee.getOffice().getOfficeCode();
		wxBusinessGroupOrgConfig.setOfficeCode(officeCode);
		wxBusinessGroupOrgConfigService.save(wxBusinessGroupOrgConfig);

		String id = wxBusinessGroupOrgConfig.getId();
		if(StringUtil.isNotEmpty(id)){
			//保存主推商家的ids
			WxBusinessGroup wxBusinessGroup = new WxBusinessGroup();
			wxBusinessGroup.setConfigGroupId(Long.valueOf(wxBusinessGroupOrgConfig.getId()));
			List<WxBusinessGroup> wxBusinessGroupList = wxBusinessGroupService.findList(wxBusinessGroup);
			if(CollectionUtil.isNotEmpty(wxBusinessGroupList)){
				WxBusinessGroup findBusinessGroup = wxBusinessGroupList.get(0);
				findBusinessGroup.setApplyBusinessIds(wxBusinessGroupOrgConfig.getWxBusinessGroup().getApplyBusinessIds());
				//保存排序
				try{
					wxBusinessGroupOrgConfigService.doSort(wxBusinessGroupOrgConfig,findBusinessGroup);
				}catch (RuntimeException e){
					e.printStackTrace();
					return renderResult(Global.FALSE, text(e.getMessage()));
				}
				//更新
				wxBusinessGroupService.save(findBusinessGroup);
			}else{
				wxBusinessGroupService.saveEmpty(wxBusinessGroupOrgConfig,officeCode);
			}
		}

		//删除缓存
		if(StringUtil.isNotEmpty(wxBusinessGroupOrgConfig.getId())) {
			WxActivity wxActivity = new WxActivity();
			wxActivity.setBusinessGroupId(Long.valueOf(wxBusinessGroupOrgConfig.getId()));
			List<WxActivity> wxActivityList = wxActivityService.findList(wxActivity);
			if (CollectionUtil.isNotEmpty(wxActivityList)) {
				for (WxActivity temp : wxActivityList) {
					String activityId = temp.getId();
					redisHandle.remove("businessList:"+activityId);
				}
			}
		}


		return renderResult(Global.TRUE, text("保存机构商家分组配置成功！"));
	}

	/**
	 * 删除机构商家分组配置
	 */
	@RequiresPermissions("wx:wxBusinessGroupOrgConfig:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig) {
		wxBusinessGroupOrgConfigService.delete(wxBusinessGroupOrgConfig);
		return renderResult(Global.TRUE, text("删除机构商家分组配置成功！"));
	}


	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		WxBusinessGroupOrgConfig wxBusinessGroupOrgConfig = new WxBusinessGroupOrgConfig();
		Employee employee = (Employee) UserUtils.getUser().getRefObj();
		wxBusinessGroupOrgConfig.setOfficeCode(employee.getOffice().getOfficeCode());
		List<WxBusinessGroupOrgConfig> list = wxBusinessGroupOrgConfigService.findList(wxBusinessGroupOrgConfig);
		for (int i=0; i<list.size(); i++){
			WxBusinessGroupOrgConfig e = list.get(i);
			// 过滤非正常的数据
			if (!TestTree.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("name", e.getGroupName());
			mapList.add(map);
		}
		return mapList;
	}
	
}